package xyz.ibenben.zhongdian.common.util;

import org.springframework.ui.Model;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.common.exception.ExceptionEnum;
import xyz.ibenben.zhongdian.common.exception.MyException;
import xyz.ibenben.zhongdian.system.entity.ajax.AjaxJson;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Response返回操作
 * Rest风格的返回json格式使用此类来操作
 * 包括responseWriter、处理错误状态等方法
 *
 * @author chenjian
 * @since 2017年10月18日下午5:17:22
 */
public class HttpServletResponseUtil{
	private HttpServletResponseUtil(){}
	
	/**
	 * responseWriter
	 * @param response 相应
	 * @param aj 参数
	 */
	public static void responseWriter(HttpServletResponse response, AjaxJson aj){
		response.setContentType("application/json; charset=utf-8");
		try {
			response.getWriter().write(aj.getJsonObject().toString());
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			try {
				aj.setSuccess(false);
				aj.setMsg("SYSTEM_ERROR");
				response.setContentType("application/json; charset=utf-8");
				response.getWriter().write(aj.getJsonObject().toString());
				response.getWriter().flush();
				response.getWriter().close();
				throw new MyException(ExceptionEnum.SYSTEMERROREXCEPTION, e);
			} catch (IOException e1) {
				throw new MyException(ExceptionEnum.SYSTEMERROREXCEPTION, e1);
			}
		}
	}

	/**
	 * 处理错误状态
	 * @param response 参数
	 * @param msg 参数
	 * @return 返回值
	 */
	public static String processErrorStatus(HttpServletResponse response, String msg){
		AjaxJson aj = new AjaxJson();
		aj.setSuccess(false);
		aj.setMsg(msg);
		responseWriter(response, aj);
		return null;
	}

	/**
	 * 处理正常状态
	 * @param response 参数
	 * @param msg 参数
	 * @return 返回值
	 */
	public static String processSuccessStatus(HttpServletResponse response, String msg){
		AjaxJson aj = new AjaxJson();
		aj.setSuccess(true);
		aj.setMsg(msg);
		responseWriter(response, aj);
		return null;
	}

	/**
	 * 处理ModelMap的状态
	 * @param map 参数
	 * @param attribute 参数
	 * @param returnStr 参数
	 * @return 返回值
	 */
	public static String processModelAndView(Model map, String attribute, String returnStr){
		map.addAttribute(Constants.MSG, attribute);
		return returnStr;
	}

}